package sanphone.com.runningschool.PersonalInfo;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

import sanphone.com.runningschool.BaseActivity;
import sanphone.com.runningschool.ForceOffline;
import sanphone.com.runningschool.InterfaceLocation;
import sanphone.com.runningschool.MainActivity;
import sanphone.com.runningschool.R;
import sanphone.com.runningschool.RequestHttp.RequestHttp;
import sanphone.com.runningschool.entity.User;


public class PersonalInfoEditActivity extends BaseActivity {
    private Button submitButton;
    private RadioGroup genderGroup;
    private String genderStr="FEMALE",nickNameStr,idStr,dormStr,contactStr,realNameStr;
    private EditText nickNameText,realNameText,dormText,contactText;
    private ImageView icon;
    SharedPreferences.Editor editorMain;
    private TextView idText;
    private String PHONE_EXCATE="^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
    private SharedPreferences sprf;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personalinfoedit);
        sprf=getSharedPreferences("data",MODE_PRIVATE);
        ForceOffline offline=new ForceOffline(sprf.getString("schoolId",null),this);
        offline.check();
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        initView();
        setData();
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nickNameStr=nickNameText.getText().toString();
                realNameStr=realNameText.getText().toString();
                dormStr=dormText.getText().toString();
                contactStr=contactText.getText().toString();
                if(nickNameStr.equals("")||realNameStr.equals("")||dormStr.equals("")||contactStr.equals("")){
                            Toast.makeText(PersonalInfoEditActivity.this,"存在空输入框!",Toast.LENGTH_SHORT).show();
                }else if(!isMatch(PHONE_EXCATE,contactStr)){
                    Toast.makeText(PersonalInfoEditActivity.this,"手机号码格式错误!",Toast.LENGTH_SHORT).show();


                }else{
                //开启线程池
                ExecutorService executorService= Executors.newSingleThreadExecutor();
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject json=new JSONObject();
                        try {
                            json.put("schoolId",idStr);
                            json.put("sex",genderStr);
                            json.put("realName",realNameStr);
                            json.put("nickName",nickNameStr);
                            json.put("phone",contactStr);
                            json.put("dormitory",dormStr);
                            RequestHttp requestHttp=new RequestHttp(InterfaceLocation.getLocation()+"setUserInfo",PersonalInfoEditActivity.this);
                            String request=requestHttp.post(json);
                            JSONObject requestJson=new JSONObject(request);
                            Log.e("data", request.toString() );
                            if(requestJson.getString("data").equals("信息修改失败")){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(PersonalInfoEditActivity.this,"信息修改失败！",Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }else{
                                // TODO: 2018/7/26 上传成功，解析回传数据，并把数据传给personInfoActivity
                                String result=requestJson.getString("data");
                                Gson gson=new Gson();
                                User user=gson.fromJson(result,User.class);

                                // TODO: 2018/7/31 资料产生修改，要再次在本地存储
                                editorMain=getSharedPreferences("data",MODE_PRIVATE).edit();
                                editorMain.putString("schoolId",user.getSchoolId());
                                editorMain.putString("userName",user.getRealName());
                                editorMain.putString("userPhone",user.getPhone());
                                editorMain.putString("nickName",user.getNickName());
                                editorMain.putString("dormitory",user.getDormitory());
                               // editorMain.putString("token",user.getToken());
                                editorMain.apply();

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(PersonalInfoEditActivity.this,"资料修改成功！",Toast.LENGTH_SHORT).show();
                                    }
                                });
                                startActivity(new Intent(PersonalInfoEditActivity.this, MainActivity.class));
                                PersonalInfoEditActivity.this.finish();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }
                });
                executorService.shutdown();
            }
            }
        });

    }

    private void setData() {
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        idStr = pref.getString("schoolId", null);
        nickNameStr = pref.getString("nickName", null);
        realNameStr = pref.getString("userName", null);
        contactStr = pref.getString("userPhone", null);
        dormStr = pref.getString("dormitory", null);
        idText.setText(idStr);
        nickNameText.setText(nickNameStr);
        realNameText.setText(realNameStr);
        contactText.setText(contactStr);
        dormText.setText(dormStr);
    }

    private void initView() {
        icon=findViewById(R.id.icon);
        submitButton=findViewById(R.id.r_commit);
       nickNameText=findViewById(R.id.r_name);
       realNameText=findViewById(R.id.r_realname);
        idText=findViewById(R.id.r_schoolId);
        dormText=findViewById(R.id.r_dorm);
        contactText=findViewById(R.id.r_contact);
        genderGroup=findViewById(R.id.sex_gp);
        genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId==R.id.female){
                    genderStr="FEMALE";
                }
                else  if(checkedId==R.id.male){
                    genderStr="MALE";
                }
                else{
                    genderStr="SECRET";
                }
            }
        });

    }

    private boolean isMatch(String pe,CharSequence input){
        return input != null && input.length() > 0 && Pattern.matches(pe, input);

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                PersonalInfoEditActivity.this.finish();
                break;
            default:
                break;
        }
        return true;
    }
}
